package com.ctsi.offlinesupport.app.rest;

import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.offlinesupport.app.rest.reponse.FlowMember;
import com.ctsi.offlinesupport.constant.FlowRole;
import com.ctsi.offlinesupport.dto.*;
import com.ctsi.offlinesupport.service.SupportFilesService;
import com.ctsi.offlinesupport.service.SupportUtilService;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.entity.OrganiseEntity;
import com.ctsi.organise.service.OrganiseEntityManager;
import com.ctsi.supportflow.app.entity.SupportFiles;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 在线支撑服务参与者
 * @author: zhangjw
 * @Date: 2018/11/8 06:51
 * @Description:
 */
@RestController
public class SupportorController {
    private static final Logger logger = LoggerFactory.getLogger(SupportorController.class);
    @Autowired
    private SupportUtilService supportUtilService;
    @Autowired
    private SupportFilesService supportFilesService;

    @Value("${file-store.upload.dir}")
    private String savePath;

    @Autowired
    private TaskService taskService;

    @Autowired
    private PersonServiceProxy userServiceProxy = OrganiseFactoryBean.getInstance().getPersonServiceProxy();

    @Autowired
    private OrganiseEntityManager organiseEntityManager;

    /**
     * 获取当前人员是否是省里的，进而明确派单方式
     * @return
     */
    @PostMapping(value = "/support-flow/send-way")
    public UnifiedResponse<Map<String,Object>> sendWay(){
        Map<String,Object> result = new HashMap<>();
        String userId = SecurityUtil.getUser().getUserId();
        // 查询当前用户是否是省公司支撑经理
        boolean isp = supportUtilService.isProvice(userId);
        if (isp) {
            result.put("isProvince",1);
        } else {
            result.put("isProvince",0);
        }
        return UnifiedResponse.ok(result);
    }

    /**
     * 地市下拉列表
     * @return
     */
    @PostMapping(value = "/support/organ-list")
    public UnifiedResponse<List<OrganDTO>> findOrganDTO(){
        String userId = SecurityUtil.getUser().getUserId();
        boolean isp = supportUtilService.isProvice(userId);
        if (isp) {
            List<OrganiseEntity> organs = organiseEntityManager.findByParentId("root");
            List<OrganDTO> result = organs.stream().map(o ->  {
                OrganDTO dto = new OrganDTO();
                dto.setOrganId(o.getPartyId());
                dto.setOrganName(o.getOrganiseName());
                return dto;
            }).collect(Collectors.toList());
            return UnifiedResponse.ok(result);
        }
        return UnifiedResponse.ok(Collections.emptyList());
    }

    /**
     * 省解决方案主任派单选人
     * @param personName
     * @param organId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/find-all-supportors")
    public UnifiedResponse<Page<AllSupportorDTO>> findAllSupportors(@RequestParam(value = "personName",required = false) String personName,
                                                                    @RequestParam(value = "organId",required = false) String organId,
                                                                    @RequestParam(value = "pageNo") Integer pageNo,
                                                                    @RequestParam(value = "roleType") String roleType,
                                                                    @RequestParam(value = "pageSize") Integer pageSize){
        String userId = SecurityUtil.getUser().getUserId();
        boolean isp = supportUtilService.isProvice(userId);

        String personNameLike = null;
        if (UtilValidate.isNotEmpty(personName)) {
            personNameLike = "%"+personName+"%";
        }
        if (UtilValidate.isEmpty(organId)) {
            organId = null;
        }

        if (!isp || "flow-depart-role".equals(roleType)) {
            // 地市派单
            Organise organ = userServiceProxy.getOrganise4User(userId);
            organId = organ.getPartyId();
        }

        return UnifiedResponse.ok(supportUtilService.findAllSuportDTO(organId,personNameLike,roleType, pageNo,pageSize));
    }

    /**
     * 产品经理发起支撑时，选择支撑经理接口
     * @param roleType
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/organ-supportors")
    public UnifiedResponse<Page<SupportorDTO>> queryOrganSupportors(@RequestParam String roleType,
                                                         @RequestParam(required = false) String userNameLike,
                                                         @RequestParam int start,
                                                         @RequestParam int pageSize) {
        UserInfo user = SecurityUtil.getUser();
        Organise organise = userServiceProxy.getOrganise4User(user.getUserId());
        Page<SupportorDTO> page = supportUtilService.findRolePerson(FlowRole.SUPPORTOR.value, organise.getPartyId(), userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * 省支撑经理
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/sheng-supportors")
    public UnifiedResponse<Page<SupportorDTO>> queryShengSupportors(@RequestParam(required = false) String userNameLike,
                                                                    @RequestParam int start,
                                                                    @RequestParam int pageSize){
        Page<SupportorDTO> page = supportUtilService.findRolePerson(FlowRole.SUPPORTOR.value, "ik1ZbQBP8KB0OOwVokE", userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * 查询支撑经理角色人
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/supportors")
    public UnifiedResponse<Page<SupportorDTO>> queryPage(@RequestParam String roleType,
                                                         @RequestParam(required = false) String userNameLike,
                                                         @RequestParam int start,
                                                         @RequestParam int pageSize) {
        UserInfo user = SecurityUtil.getUser();
        Organise organise = null;
        if (roleType.equals(FlowRole.SUPPORTOR.value)) {
            organise = userServiceProxy.getDepart4User(user.getUserId());
        } else if (roleType.equals(FlowRole.DEPART.value)) {
            organise = userServiceProxy.getOrganise4User(user.getUserId());
        }

        Page<SupportorDTO> page = supportUtilService.findRolePerson(roleType, organise.getPartyId(), userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * 部门派单时查询该部门下的支撑经理
     */
    @PostMapping(value = "/support/depart-supportors")
    public UnifiedResponse<Page<SupportorDTO>> queryDepartSupport(
                                                                  @RequestParam(required = false) String userNameLike,
                                                                  @RequestParam int start,
                                                                  @RequestParam int pageSize){
        UserInfo user = SecurityUtil.getUser();
        Organise organise = userServiceProxy.getDepart4User(user.getUserId());
        Page<SupportorDTO> page = supportUtilService.findRolePerson(FlowRole.SUPPORTOR.value, organise.getPartyId(), userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * 查询协同部门接口人
     *
     * @param departNameLike
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/assterleaders")
    public UnifiedResponse<Page<AssterDepartDTO>> queryAssertLeader(@RequestParam(required = false) String departNameLike,
                                                                    @RequestParam(required = false) String userNameLike,
                                                                    @RequestParam int start,
                                                                    @RequestParam int pageSize) {

        UserInfo user = SecurityUtil.getUser();
        Page<AssterDepartDTO> page = supportUtilService.queryAssterLeader(FlowRole.XIETONG.value, user.getUserId(), departNameLike, userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }



    /**
     * 查询本部门专家列表
     *
     * @param userNameLike
     * @param start
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/support/assters")
    public UnifiedResponse<Page<AssterDTO>> queryAsster(@RequestParam(required = false) String userNameLike,
                                                        @RequestParam int start,
                                                        @RequestParam int pageSize) {
        Page<AssterDTO> page = supportUtilService.findAssert(FlowRole.ASSTER.value, SecurityUtil.getUser().getUserId(), userNameLike, start, pageSize);
        return UnifiedResponse.ok(page);
    }

    /**
     * 上传附件（支撑方案）
     * @param taskId
     * @param file
     * @return
     */
    @PostMapping(value = "/support/upload-files")
    public UnifiedResponse uploadfile(@RequestParam(value = "taskId") String taskId,
                                        @RequestParam("file") MultipartFile file) {

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstId = task.getProcessInstanceId();
        String suffix = "";
        if (file.isEmpty()) {
            return UnifiedResponse.error("900004", "请上传PDF文件");
        } else {
            String fileName = file.getOriginalFilename();
            logger.warn("upload file name is {}", fileName);
            suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!suffix.equalsIgnoreCase("pdf")) {
                return UnifiedResponse.error("900004", "请上传PDF文件");
            }
        }
        String uuid = UUIDGenerator.getId();
        String ppth = "supportfiles/";

        String destPath = savePath + ppth;
        InputStream in = null;
        OutputStream out = null;
        String filepath = ppth + uuid + "." + suffix;
        try {
            File dest = new File(destPath);
            if (!dest.exists()) {
                dest.mkdirs();
            }
            File ffile = new File(savePath + filepath);

            in = file.getInputStream();
            out = new FileOutputStream(ffile);
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }

            SupportFiles sfile = new SupportFiles();
            sfile.setId(UUIDGenerator.getId());
            sfile.setAdjunctId(uuid);
            sfile.setFileName(file.getOriginalFilename());
            sfile.setFileSize(Long.valueOf(file.getBytes().length));
            sfile.setSavePath(filepath);
            sfile.setUserId(SecurityUtil.getUser().getUserId());
            sfile.setUploadTime(System.currentTimeMillis());
            sfile.setTaskId(taskId);
            sfile.setProcessInstId(processInstId);
            supportFilesService.insertSupportFiles(sfile);
            Map<String, String> result = new HashMap<>();
            result.put("name", file.getOriginalFilename());
            result.put("url", file.getOriginalFilename());
            result.put("fileId", uuid);
            result.put("url", "/api/org/support/upload-files/" + uuid);
            return UnifiedResponse.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return UnifiedResponse.ok();
    }


    @GetMapping(value = "/support/upload-files/{fileId}")
    public void downLoad(@PathVariable("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
        SupportFiles file = supportFilesService.getFilesByAdjunctId(fileId);
        String finalUrl = savePath + file.getSavePath();

        File f = new File(finalUrl);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(f);
            UtilHttp.streamContentToBrowser(request, response, inputStream, "application/pdf", file.getFileName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            UtilMisc.closeObjNoExc(inputStream);
        }


    }

    /**
     * 返回中心主任列表
     * @return
     */
    @PostMapping(value = "/support/send-roles")
    public UnifiedResponse<List<FlowMember>> findFlowRole4Send(){
        return UnifiedResponse.ok(supportUtilService.findFlowMember(SecurityUtil.getUser().getUserId()));
    }

}
